import request from "@/utils/request";

interface VoiceRecognitionOptions {
  language?: string;
  timeout?: number;
}

interface VoiceRecognitionResponse {
  code: number;
  message: string;
  data: string;
}

// 获取语音识别结果
/**
 * 语音识别API封装
 * @param audioBlob 录音的Blob对象
 * @param options 配置选项
 * @returns 识别结果文本
 * @throws 当请求失败或识别失败时抛出错误
 */
export const fetchVoiceRecognition = async (
  audioBlob: Blob,
  options: VoiceRecognitionOptions = {}
): Promise<string> => {
  const { language = "chinese", timeout = 3000000 } = options; // 50分钟超时

  try {
    // 1. 确保blob是有效的WAV文件
    let processedBlob = audioBlob;
    if (!audioBlob.type.includes("audio/wav")) {
      processedBlob = new Blob([audioBlob], { type: "audio/wav" });
    }

    // 创建AbortController和保活定时器
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    // 保活机制 - 每30秒发送一个空包
    const keepAliveInterval = setInterval(() => {
      if (controller.signal.aborted) return;
      // 可以发送心跳请求或不做任何操作
    }, 30000);

    // 2. 准备FormData
    const formData = new FormData();
    formData.append("audio", processedBlob, "recording_8k.wav");
    formData.append("language", language);

    // 4. 发送请求
    const response = await request
      .fetchWithAuth("/api/ai/voice/recognize", {
        method: "POST",
        body: formData,
        // 注意：不手动设置Content-Type
        signal: controller.signal,
      })
      .finally(() => {
        clearTimeout(timeoutId);
        clearInterval(keepAliveInterval);
      });

    // 4. 处理响应
    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      throw new Error(error.message || `请求失败: ${response.status}`);
    }

    const result: VoiceRecognitionResponse = await response.json();

    if (result.code !== 200) {
      throw new Error(result.message || "语音识别失败");
    }

    return result.data;
  } catch (error) {
    console.error("语音识别请求错误:", error);
    throw new Error(
      error instanceof Error ? error.message : "语音识别请求发生未知错误"
    );
  }
};
